package cn.thoughtworks.school.response;

import cn.thoughtworks.school.entities.Serial;
import cn.thoughtworks.school.entities.Video;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;

import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SerialResponse {
  private Long id;
  private String coverUrl;
  private String title;
  private String description;
  private Boolean isAllVisible;
  private Boolean isPublic;
  private Boolean isRelease;
  private Boolean isNeedSubscribe;
  private String username;
  @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
  private Date createTime;

  private List<SimpleVideoResponse> videos;

  public static SerialResponse build(Map user, Serial serial, boolean isCurrentUserNeedSubscribe, List<SimpleVideoResponse> simpleVideoResponses) {
    if (isCurrentUserNeedSubscribe) {
      hideVideosUrl(simpleVideoResponses);
    }
    return SerialResponse.builder()
        .id(serial.getId())
        .coverUrl(serial.getCoverUrl())
        .title(serial.getTitle())
        .description(serial.getDescription())
        .isAllVisible(serial.getIsAllVisible())
        .isPublic(serial.getIsPublic())
        .isRelease(serial.getIsRelease())
        .isNeedSubscribe(isCurrentUserNeedSubscribe)
        .createTime(serial.getCreateTime())
        .username(user.get("name").toString())
        .videos(simpleVideoResponses).build();
  }

  private static List<SimpleVideoResponse> hideVideosUrl(List<SimpleVideoResponse> videos) {
    return videos.stream()
      .map(video -> {
        video.setUrl("");
        return video;
      })
      .collect(Collectors.toList());
  }
}
